﻿var lastRows = [];
var columnDependencies = [];
var dependency = null;
var newButtonsAdded = [];

//$(document).ready(function() {
//    $(document).ajaxError(function(e, xhr, settings, exception) {
//        alert('response: ' + xhr.responseText);
//    });
//});

function debugObject(obj) {
	var text = '';

	for (var prop in obj) {
		if (typeof (obj[prop]) != 'function' && prop != 'searchFilter') {
			text += prop + '[' + obj[prop] + ']\r\n';
		}
	}

	alert(text);
}

function addNewButton(gridId, pagerId) {
	for (var i = 0; i < newButtonsAdded.length; i++) {
		if (newButtonsAdded[i] == pagerId) {
			return;
		}
	}

	var grid = $("#" + gridId);

	grid.jqGrid('navButtonAdd', '#' + pagerId, {
		caption: "",
		buttonicon: 'ui-icon-circle-plus',
		onClickButton: function () {
			var dataRow = {
				ID: "-2"
			};

			if (grid.addRowData(-2, dataRow, "first")) {
				editRow(gridId, -2);
			}
		},
		title: "New Button",
		position: "last"
	});

	newButtonsAdded.push(pagerId);
}

function showSubGridAddNewButton(subgrid_id) {
	var subgrid_table_id = subgrid_id + '_t';

	addNewButton(subgrid_table_id, 'p_' + subgrid_table_id);
}

function initEditGrid(gridId) {
    loadEditActionIcons(gridId);
    //addNewButton(gridId, gridId + '_pager');
}

function initChildEditGrids(gridId) {
    var grid = $("#" + gridId);
    var rowIds = grid.jqGrid('getDataIDs');

    for (var i = 0; i < rowIds.length; i++) {
        var subgrid_table_id = gridId + '_' + rowIds[i] + '_t';
    
        loadEditActionIcons(subgrid_table_id);
    }
}

function loadEditActionIcons(gridId) {
    var grid = $("#" + gridId);
    var rowIds = grid.jqGrid('getDataIDs');

    for (var i = 0; i < rowIds.length; i++) {
    	var isEdit = grid.jqGrid('getCell', rowIds[i], 'Edit');

    	if (isEdit) {
    		grid.jqGrid('setCell', rowIds[i], 'Edit', edit_delete(gridId, rowIds[i]));
    	}
    }
}

function setLastRow(gridId, rowId, rowData) {
    for (var i = 0; i < lastRows.length; i++) {
        if (lastRows[i][0] == gridId) {
            lastRows[i][1] = rowId;
            lastRows[i][2] = rowData;
            return;
        }
    }

    var arr = new Array(2);
    arr[0] = gridId;
    arr[1] = rowId;
    arr[2] = rowData;

    lastRows.push(arr);
}

function getLastRow(gridId, rowId) {
    for (var i = 0; i < lastRows.length; i++) {
        if (lastRows[i][0] == gridId) {
            return lastRows[i];
        }
    }

    return;
}

function editRow(gridId, rowId) {
    var grid = $("#" + gridId);
    var lastRow = getLastRow(gridId, rowId);

    if (lastRow) {
        var lastId = lastRow[1];
        
        if (rowId && rowId != lastId) {
            restoreRow(gridId, lastId);
        }
    }

    var initialRowData = $("#" + gridId).jqGrid('getRowData', rowId);
    
    grid.jqGrid('setSelection', rowId);
    grid.jqGrid('editRow', rowId, true);
    grid.jqGrid('setCell', rowId, 'Edit', save_cancel(gridId, rowId));

    setLastRow(gridId, rowId, initialRowData);
 
    populateDependentColumns(gridId, rowId);
}

function populateDependentColumnsDialogue(grid) {
    var gridId = $(grid).attr('id');
    var rowId = -1;

    if (gridId.indexOf('_') > -1) {
        var parts = gridId.split('_');

        if (parts.length == 4 && parts[3].indexOf('t') == 0) {
            gridId = parts[3].substr(1);
        }
    }

//    if (rowId != -1) {
//        var initialRowData = $("#" + gridId).jqGrid('getRowData', rowId);
//        setLastRow(gridId, rowId, initialRowData);
//    }
    
    populateDependentColumns(gridId, rowId);
}

function populateDependentColumns(gridId, rowId) {
    for (var i = 0; i < columnDependencies.length; i++) {
        var cd = columnDependencies[i];

		if (cd.gridId == gridId) {
        
            updateDependentField(rowId, cd);
            bindColumnChangeEvent(rowId, cd);
        }
    }
}

function bindColumnChangeEvent(rowId, cd) {
    $("#" + rowId + "_" + cd.parentColumn).change(function(e) {
        updateDependentField(rowId, cd);
        bindColumnChangeEvent(rowId, cd);
    });
}

function updateDependentField(rowId, cd) {
	var element;

	if (rowId == -1) {
		element = document.getElementById(cd.childColumn);
		cd.parentField = $("#" + cd.parentColumn);
		cd.childField = $("#" + cd.childColumn);
	}
	else {
		element = document.getElementById(rowId + "_" + cd.childColumn);
		cd.parentField = $("#" + rowId + "_" + cd.parentColumn);
		cd.childField = $("#" + rowId + "_" + cd.childColumn);

		cd.initialRowData = getLastRow(cd.gridId, rowId)[2];
	}

	cd.parentFieldValue = cd.parentField.val();

	if (!cd.parentFieldValue) {
		cd.parentFieldValue = cd.initialRowData[cd.parentColumn];
	}

	if (cd.parentFieldValue != cd.nullParentDataValue && cd.parentFieldValue != '-2') {
		if (element == '[object HTMLSelectElement]') {
			updateDependentDropDown(rowId, cd);
		}
		else if (element == '[object HTMLInputElement]') {
			updateDependentTextBox(rowId, cd);
		}
	}
}

function updateDependentDropDown(rowId, cd) {
	if (cd.loadingText) {
		cd.childField.html('<option value="-1">' + cd.loadingText + '</option>').attr('disabled', 'disabled');
	}

    $.ajax({
        url: cd.url,
        type: "POST",
        data: { 'parentFieldValue': cd.parentFieldValue, 'initialChildData': (cd.initialRowData) ? cd.initialRowData[cd.childColumn] : '' },
        success: function(response) {
            var collection = eval(response);
            var html = '';

            if (cd.headingText) {
                html = '<option value="-1">' + cd.headingText + '</option>';
            };

            $(collection).each(function(i, option) {
                html += '<option value="' + option[cd.dataValueField] + '"';

                if (cd.initialRowData[cd.childColumn].toLowerCase() == option[cd.dataTextField].toLowerCase()) {
                    html += ' selected="selected"';
                }

                html += '>' + option[cd.dataTextField] + '</option>';
            });

            cd.childField.removeAttr("disabled").html(html);

            cd.onChange(rowId, cd);
        }
    });
}

function updateDependentTextBox(rowId, cd) {
    if (cd.loadingText) {
        cd.childField.attr('value', cd.loadingText).attr("disabled", "disabled");
    }

    $.ajax({
        url: cd.url,
        type: "POST",
        data: { 'parentFieldValue': cd.parentFieldValue, 'initialChildData': (cd.initialRowData) ? cd.initialRowData[cd.childColumn] : '' },
        success: function(response) {
            if (response != 'undefined' && response != '') {
                var val = response[cd.dataValueField];

                cd.childField.attr('value', val);
            }
            else if (cd.initialRowData) {
                cd.childField.attr('value', cd.initialRowData[cd.childColumn])
            }

            cd.childField.removeAttr("disabled");

            cd.onChange(rowId, cd);
        }
    });
}

function saveRow(gridId, rowId) {
    var grid = $("#" + gridId);

    grid.jqGrid('saveRow', rowId);

    if (rowId != -2) {
        restoreRow(gridId, rowId);
    }

    grid.trigger('reloadGrid');
}

function deleteRow(gridId, rowId) {
    var grid = $("#" + gridId);

    if (grid.jqGrid('delGridRow', rowId)) {
        grid.jqGrid('delRowData', rowId);
    }
}

function restoreRow(gridId, rowId) {
    var grid = $("#" + gridId);

    if (rowId == -2) {
        grid.jqGrid('delRowData', rowId);
    }
    else {
        grid.jqGrid('restoreRow', rowId);
        grid.jqGrid('setCell', rowId, 'Edit', edit_delete(gridId, rowId));
    }
}

function edit_delete(gridId, rowId) {
    return edit_link('editRow', 'edit', gridId, rowId) + edit_link('deleteRow', 'delete', gridId, rowId);
}

function save_cancel(gridId, rowId) {
    return edit_link('saveRow', 'save', gridId, rowId) + edit_link('restoreRow', 'cancel', gridId, rowId);
}

function edit_link(fnName, linkText, gridId, rowId) {
    var cssClass;

    switch (fnName) {
        case 'editRow': cssClass = 'ui-icon-pencil'; break;
        case 'deleteRow': cssClass = 'ui-icon-trash'; break;
        case 'saveRow': cssClass = 'ui-icon-disk'; break;
        case 'restoreRow': cssClass = 'ui-icon-cancel'; break;
        default: break;
    }

    return "<a href='#' onclick='" + fnName + "(\"" + gridId + "\", \"" + rowId + "\");' class='ui-icon " + cssClass + "' style='float:left; margin:0 5px 0 5px'></a>";
}